<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品编号" prop="snId">
        <el-input
          v-model="queryParams.snId"
          placeholder="请输入商品编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:period:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:period:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="periodList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编号" align="center" prop="snId" />
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <el-table-column label="规格" align="center" prop="specification" />
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="即时库存" align="center" prop="timeinventory" />
      <el-table-column label="可用库存" align="center" prop="availablestock" />
      <el-table-column label="批次" align="center" prop="batch" />
      <el-table-column label="生产日期" align="center" prop="manufacture" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.manufacture, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保质期" align="center" prop="period" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.period, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="到期日" align="center" prop="duedate" />
      <el-table-column label="预警天数" align="center" prop="days" />
      <el-table-column label="预警日期" align="center" prop="date" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="剩余到期天数" align="center" prop="remainingDays" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:period:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:period:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【保质期预警】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品编号" prop="snId">
          <el-input
            v-model="form.snId"
            placeholder="请输入商品编号"
            disabled="true"
          />
        </el-form-item>
        <el-form-item label="规格" prop="specificationId">
          <el-select
            v-model="form.specificationId"
            placeholder="请选择规格"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in specOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseId">
          <el-select v-model="form.warehouseId" placeholder="请选择仓库名称" style="width: 100%">
            <el-option
              v-for="warehouse in warehouseOptions"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="即时库存" prop="timeinventory">
          <el-input v-model="form.timeinventory" placeholder="请输入即时库存" />
        </el-form-item>
        <el-form-item label="可用库存" prop="availablestock">
          <el-input v-model="form.availablestock" placeholder="请输入可用库存" />
        </el-form-item>
        <el-form-item label="批次" prop="batch">
          <el-input v-model="form.batch" placeholder="请输入批次" />
        </el-form-item>
        <el-form-item label="生产日期" prop="manufacture">
          <el-date-picker clearable
                          v-model="form.manufacture"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择生产日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="保质期" prop="period">
          <el-date-picker clearable
                          v-model="form.period"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择保质期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到期日" prop="duedate">
          <el-input v-model="form.duedate" placeholder="请输入到期日" />
        </el-form-item>
        <el-form-item label="预警天数" prop="days">
          <el-input v-model="form.days" placeholder="请输入预警天数" />
        </el-form-item>
        <el-form-item label="预警日期" prop="date">
          <el-date-picker clearable
                          v-model="form.date"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择预警日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择商品对话框 -->
    <el-dialog title="选择商品" :visible.sync="goodsSelectVisible" width="70%" append-to-body>
      <el-form :model="goodsQueryParams" ref="goodsQueryForm" size="small" :inline="true">
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="goodsQueryParams.name"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter.native="handleGoodsQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleGoodsQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetGoodsQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="goodsLoading" :data="goodsList" @row-click="handleGoodsSelect">
        <el-table-column label="商品编号" align="center" prop="sn" />
        <el-table-column label="商品名称" align="center" prop="name" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-check"
              @click="handleGoodsSelect(scope.row)"
            >选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="goodsTotal>0"
        :total="goodsTotal"
        :page.sync="goodsQueryParams.pageNum"
        :limit.sync="goodsQueryParams.pageSize"
        @pagination="getGoodsList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listPeriod, getPeriod, delPeriod, addPeriod, updatePeriod, specList } from "@/api/system/period";
import { listGoods } from "@/api/goods/goods";
import { listWarehouse } from "@/api/system/inventory";

export default {
  name: "Period",
  data() {
    return {
      goodsSelectVisible: false,
      goodsLoading: false,
      goodsList: [],
      goodsTotal: 0,
      goodsQueryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      specOptions: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      periodList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        snId: null,
        specificationId: null,
        warehouseId: null,
        unit: null,
        timeinventory: null,
        availablestock: null,
        warehouseOptions: [],
        batch: null,
        manufacture: null,
        period: null,
        duedate: null,
        days: null,
        date: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        snId: [
          { required: true, message: "商品编号不能为空", trigger: "blur" }
        ],
        specificationId: [
          { required: true, message: "规格不能为空", trigger: "blur" }
        ],
        warehouseId: [
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],
        manufacture: [
          { required: true, message: "生产日期不能为空", trigger: "blur" }
        ],
        period: [
          { required: true, message: "保质期不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getWarehouseOptions();
    this.getSpecList();
  },
  methods: {
    getSpecList() {
      specList().then(response => {
        console.log("规格列表响应:", response);
        this.specOptions = response.data || [];
      }).catch(error => {
        console.error("获取规格列表失败:", error);
        this.$message.error("获取规格列表失败");
        this.specOptions = [];
      });
    },
    // 新增商品选择相关方法
    handleGoodsQuery() {
      this.goodsQueryParams.pageNum = 1;
      this.getGoodsList();
    },
    /** 获取仓库列表 */
    getWarehouseOptions() {
      listWarehouse().then(response => {
        response.rows.forEach(warehouse => {
          warehouse.warehouseName = warehouse.name;
        });
        this.warehouseOptions = response.rows;
      });
    },
    resetGoodsQuery() {
      this.resetForm("goodsQueryForm");
      this.handleGoodsQuery();
    },
    getGoodsList() {
      this.goodsLoading = true;
      listGoods(this.goodsQueryParams).then(response => {
        console.log(response);
        this.goodsList = response.rows;
        this.goodsTotal = response.total;
        this.goodsLoading = false;
      });
    },
    handleGoodsSelect(row) {
      this.form.snId = row.sn;
      this.form.goodsName = row.name;
      this.form.specificationId = null;
      this.form.specification = null;
      this.goodsSelectVisible = false;

      // 在选择完商品后，再显示添加保质期预警的弹窗
      this.open = true;
      this.title = "添加保质期预警";
    },
    // 修改handleAdd方法
    handleAdd() {
      this.reset();
      this.goodsSelectVisible = true; // 先显示选择商品的弹窗
      this.getGoodsList();
    },
    getList() {
      this.loading = true;
      listPeriod(this.queryParams).then(response => {
        console.log(response);
        this.periodList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        snId: null,
        specificationId: null,
        warehouseId: null,
        unit: null,
        timeinventory: null,
        availablestock: null,
        batch: null,
        manufacture: null,
        period: null,
        duedate: null,
        days: null,
        date: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPeriod(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePeriod(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPeriod(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function() {
        return delPeriod(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/period/export', {
        ...this.queryParams
      }, `period_${new Date().getTime()}.xlsx`);
    }
  }
};
</script>
